package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.Friend;
import com.tanhua.manage.domain.mongo.Publish;


import com.tanhua.manage.domain.mongo.RecommendQuanzi;
import com.tanhua.manage.domain.mongo.TimeLine;
import com.tanhua.manage.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;
/**
 * 发布动态
 */
    @Override
    public void add(Publish publish) {
        Long userId = publish.getUserId();
        //生成动态的id
        ObjectId objectId = new ObjectId();
        publish.setId(objectId);
        long timeMillis = System.currentTimeMillis();
        publish.setCreated(timeMillis);
        mongoTemplate.insert(publish);

        //生成自己的时间线表
        TimeLine timeline = new TimeLine();
        timeline.setPublishId(objectId);
        timeline.setCreated(timeMillis);
        timeline.setUserId(userId);
        String collectionName = "quanzi_time_line_" + userId;

        mongoTemplate.insert(timeline,collectionName);

        //查询好友，添加到好友的时间线列表里
        Query userFreandQuery = new Query(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(userFreandQuery, Friend.class);
        if (!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(userId);
                timeLine.setPublishId(objectId);
                timeLine.setCreated(timeMillis);
                String friendCollectionName = "quanzi_time_line_"+ friend.getFriendId();
                mongoTemplate.insert(timeLine,friendCollectionName);
            }
        }
    }

    /**
     * 查询好友动态
     */
    @Override
    public PageResult findFriendPublishByTimeline(Long userId, Long page, Long pageSize) {

        //查询登陆用户自己的时间线表，分页查询
        //构建条件
        Query timeLineQuery = new Query();
        //集合名称
        String timeLineCollectionName = "quanzi_time_line_"+userId;
        //查询总记录数
        long total = mongoTemplate.count(timeLineQuery, timeLineCollectionName);
        //先创建用于接收pulish的集合,否则if外用不了
        List<Publish> publishList = new ArrayList<>();
        //大于0，说明有数据，才往下走
        if (total>0){
            // 设置按创建的时间降序
            timeLineQuery.with(Sort.by(Sort.Order.desc("created")));
            // 分页
            timeLineQuery.skip((page-1)*pageSize).limit(pageSize.intValue());

            List<TimeLine> timeLineList = mongoTemplate.find(timeLineQuery, TimeLine.class,timeLineCollectionName);

            List<ObjectId> publishIds = timeLineList.stream().map(TimeLine::getPublishId).collect(Collectors.toList());

            Query publishQuery = new Query(Criteria.where("id").in(publishIds));
             publishList = mongoTemplate.find(publishQuery, Publish.class);

        }
        return PageResult.pageResult(page,pageSize,publishList,total);
    }

    /**
     * 查询推荐动态
     * @param loginUserId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findRecommendPublishByTimeline(Long loginUserId, Long page, Long pageSize) {

        //构建条件
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        Long total = mongoTemplate.count(query, RecommendQuanzi.class);

        List<Publish> publishList = new ArrayList<>();
        if (total > 0){
            query.with(Sort.by(Sort.Order.desc("created")));
            query.skip((page-1)*pageSize).limit(pageSize.intValue());

            List<RecommendQuanzi> recommendQuanziList = mongoTemplate.find(query, RecommendQuanzi.class);

            List<ObjectId> publishIds = recommendQuanziList.stream().map(RecommendQuanzi::getPublishId).collect(Collectors.toList());

            Query publishQuery = new Query(Criteria.where("id").in(publishIds));
            publishList = mongoTemplate.find(publishQuery, Publish.class);

        }
        return PageResult.pageResult(page,pageSize,publishList,total);
    }

    @Override
    public PageResult findMyPublishListByTimeLine(Long loginUserId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        String timeLineCollectionName = "quanzi_time_line_"+loginUserId;
        long count = mongoTemplate.count(query, timeLineCollectionName);
        List<Publish> publishList = new ArrayList<>();
        if (count>0){
            // 设置按创建的时间降序
            query.with(Sort.by(Sort.Order.desc("created")));
            // 分页
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, timeLineCollectionName);

            List<ObjectId> objectIds = timeLineList.stream().map(TimeLine::getPublishId).collect(Collectors.toList());
            Query publishQuery = new Query(Criteria.where("id").in(objectIds));
            publishList = mongoTemplate.find(publishQuery, Publish.class);
        }
        return PageResult.pageResult(page,pageSize,publishList,count);
    }

    /**
     * 查询单条动态
     * @return
     */
    @Override
    public Publish findById(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }
}
